// 引入文档模型
const BookModel = require('./BookModel')
// 引入await-to-js处理错误
const {
    to
} = require('await-to-js')

// 查找出所有的图书
findAllBooks = async () => {
    const [err, data] = await to(BookModel.find())
    if (err) {
        return {
            code: 404,
            message: '获取图书列表失败!'
        }
    }
    return {
        code: 200,
        data,
        message: '获取图书列表成功~'
    }
}

// 查找出id对应的图书
findCurrentBook = async (_id) => {
    const [err, data] = await to(BookModel.findById({
        _id
    }))
    if (err) {
        return {
            code: 404,
            message: '查找图书失败!'
        }
    }
    return {
        code: 200,
        data,
        message: '查找图书成功~'
    }

}

// 向数据库中添加图书
addBook = async (book) => {
    const [err, data] = await to(BookModel.create(book))
    if (err) {
        return {
            code: 404,
            message: '添加图书失败!'
        }
    }
    return {
        code: 200,
        data,
        message: '添加图书成功~'
    }
}

// 更新数据库中的对应图书
updateBook = async (book) => {
    const [err, data] = await to(BookModel.updateOne({
        _id: book._id
    }, book))
    if (err) {
        return {
            code: 404,
            message: '更新图书失败!'
        }
    }
    return {
        code: 200,
        data,
        message: '更新图书成功~'
    }
}

// 删除数据库中对应id的图书
removeBook = async (_id) => {
    const [err, data] = await to(BookModel.deleteOne({
        _id
    }))
    if (err) {
        return {
            code: 404,
            message: '删除图书失败!'
        }
    }
    return {
        code: 200,
        data,
        message: '删除图书成功~'
    }
}

// 向外暴露接口
module.exports = {
    findAllBooks,
    findCurrentBook,
    addBook,
    updateBook,
    removeBook
}